﻿using System.IO;
using System.Threading.Tasks;
using TiaoTiaoCode.AutoUpdate.Common.Exceptions;
using TiaoTiaoCode.AutoUpdate.DbCore.Entities;
using TiaoTiaoCode.AutoUpdate.ServiceCore.IServices;
using TiaoTiaoCode.BasicDbCore;

namespace TiaoTiaoCode.AutoUpdate.ServiceCore.Services
{
    /// <summary>
    /// 程序文件服务
    /// </summary>
    public class ProgramFileDetailService : Repository<ProgramFileDetail>, IProgramFileDetailService
    {
        /// <summary>
        /// 根据文件Id获取文件在服务器的路径
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        public async Task<string> GetFileCalatog(string fileId)
        {
            var fileInfo = await Context.Queryable<ProgramFileDetail>()
                                    .Includes(t => t.MainProgram)
                                    .Where(t => t.Id == fileId && t.DelFlag == "0")
                                    .FirstAsync();

            if (fileInfo == null) throw new CustomException($"未找到文件【{fileId}】");

            var main = fileInfo.MainProgram;
            if (main == null) throw new CustomException($"文件异常，无对应主程序信息");

            // 主程序根目录+文件相对目录
            var catalog = Path.Combine(main.Catalog, fileInfo.Catalog!.TrimStart('\\'), fileInfo.FileName);

            return catalog;
        }
    }
}
